package cn.tedu.boyou.comment.service.impl;

import cn.tedu.boyou.comment.domain.ReviewComment;
import cn.tedu.boyou.comment.repository.IReviewCommentRepository;
import cn.tedu.boyou.comment.service.IReviewCommentService;
import cn.tedu.boyou.common.query.ReviewCommentQuery;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class ReviewCommentServiceImpl implements IReviewCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IReviewCommentRepository dao;


    public ReviewComment save(ReviewComment review) {
        review.setCreateTime(new Date());
        dao.save(review);

        return review;
    }

    public Page<ReviewComment> query(ReviewCommentQuery qo) {
        Query query = new Query();
        Criteria criteria = null;
        /*if(qo.getSightId() != -1){
            criteria = Criteria.where("sightId").is(qo.getSightId());
        }else {
            criteria = Criteria.where("sightId").ne(qo.getSightId());
        }
*/
       query.addCriteria(criteria);

        long total = mongoTemplate.count(query, ReviewComment.class);
        if(total == 0){
            return Page.empty();
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() -1, qo.getPageSize());
        query.with(pageable);
        Sort createTime = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(createTime);
        List<ReviewComment> list = mongoTemplate.find(query, ReviewComment.class);

        return new PageImpl<ReviewComment>(list,pageable,total);
    }


    public ReviewComment getReviewCommentById(String rid) {
         return dao.findById(rid).get();
    }



}
